/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.menu.file;

import com.thoughtworks.xstream.XStream;
import data.DataVector;
import data.classDiagram.Entity;
import org.pushingpixels.flamingo.api.common.JCommandButton;
import org.pushingpixels.flamingo.api.common.icon.ImageWrapperResizableIcon;
import org.pushingpixels.flamingo.api.ribbon.RibbonApplicationMenuEntryPrimary;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Student
 */
public class ExportToXmlItem extends RibbonApplicationMenuEntryPrimary implements ActionListener {

    private final JFileChooser fc = new JFileChooser();

    public ExportToXmlItem() {
        super(ImageWrapperResizableIcon.getIcon(
		        ClassLoader.getSystemClassLoader().getResource("icons/save.png"),
		        new Dimension(16, 16)), "Save", null, JCommandButton.CommandButtonKind.ACTION_ONLY);

	    this.mainActionListener = this;

        fc.setFileFilter(new FileNameExtensionFilter("Class diagram editor files (*.cde)", "cde"));
        fc.setAcceptAllFileFilterUsed(false);
    }

    public void actionPerformed(ActionEvent e) {
        int returnVal = fc.showSaveDialog(null);
        PrintWriter pw = null;
        ObjectOutputStream out = null;
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            String filePath = file.getPath();

            if(!filePath.toLowerCase().endsWith(".cde"))
            {
                file = new File(filePath + ".cde");
            }


            try {
                if (!file.exists()) {
                    file.createNewFile();
                }

                FileWriter fw = new FileWriter(file);
                pw = new PrintWriter(fw);
                XStream stream = new XStream();
                stream.autodetectAnnotations(true);
                out = stream.createObjectOutputStream(pw, "data-vector");
                for (Entity entity : DataVector.getInstance().getEntityList()) {
                    out.writeObject(entity);
                }

                JOptionPane.showMessageDialog(null, "Saved!");
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                if (out != null){
                    try{
                        out.close();
                    } catch (IOException ex2){

                    }
                }
            }
        }
    }
}
